package com.spzx.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class AlipayServiceImpl implements IAlipayService {

    @Autowired
    IPaymentInfoService paymentInfoService;

    @Autowired
    AlipayClient alipayClient;


    @Override
    public String submitAlipay(String orderNo) throws AlipayApiException {
        //1.封装支付信息并保存
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(orderNo);

        //2.调用支付宝支付api接口，返回form表单
        //参考官方提供接口文档：https://opendocs.alipay.com/open/29ae8cb6_alipay.trade.wap.pay?scene=21&pathHash=1ef587fd
        // 生产二维码
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        // 同步回调
        // return_payment_url=http://sph-payment.atguigu.cn/alipay/callback/return
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url); //同步地址，用来通知用户支付是否成功
        // 异步回调  判断支付是否成功，以异步回调为主。
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);//在公共参数中设置回跳和通知地址     异步通知，用来通知尚品甄选后端，更新业务数据。
        // 参数
        // 声明一个map 集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("out_trade_no",paymentInfo.getOrderNo()); //订单号
        map.put("product_code","QUICK_WAP_WAY"); //手机网站支付类型
        //map.put("total_amount",orderInfo.getTotalAmount());
        map.put("total_amount","0.01");
        map.put("subject",paymentInfo.getContent());

        alipayRequest.setBizContent(JSON.toJSONString(map));

        return alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单;
    }


    @Override
    public void closePayment(String orderNo) {
        //1.查询交易记录
        PaymentInfo paymentInfo = paymentInfoService.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        //2.判断交易记录是否存在，并且未支付
        if (paymentInfo!=null && "0".equals(paymentInfo.getPaymentStatus())) {
            //3 产生本地交易记录 要进行关闭
            paymentInfo.setPaymentStatus("-1");
            paymentInfoService.updateById(paymentInfo);
        }
    }
}
